package cn.apotato.modules.test.controller;

import cn.apotato.common.model.UserInfo;
import cn.apotato.common.utils.RandomUtils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.ListUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 简单excel控制器
 *
 * @author 胡晓鹏
 * @date 2023/05/23
 */
@RequestMapping("easy-excel")
@RestController
public class EasyExcelController {
    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), UserInfo.class).sheet("模板").doWrite(data());
    }


    public static List<UserInfo> data() {
        List<UserInfo> list = ListUtils.newArrayList();
        for (int i = 0; i < 10; i++) {
            UserInfo data = new UserInfo();
            data.setName("字符串" + i);
            data.setGrade((int) (Math.random() * 1000 / 100));
            // 随机获取一个境界
            String level = RandomUtil.randomEle(CollUtil.newArrayList("凡人", "练气", "筑基", "金丹", "元婴", "化神"));
            data.setLevel(level);
            data.setPhone(RandomUtils.randomPhoneNum());
            list.add(data);
        }
        return list;
    }


    public static void main(String[] args) {
        List<UserInfo> data = EasyExcelController.data();
        System.out.println(JSONUtil.toJsonStr(data));
    }
}
